/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-04 18:00:36
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-11 20:52:10
 * @FilePath: /operator-manager/src/access.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { matchPermission } from '@/utils/permission';

export enum PermissionType {
  MENU = 1,
  BUTTON = 2,
}

interface IPermissionItemProps {
  access: string;
  type: PermissionType;
}
export default function access(initialState: { currentUser: any } | undefined) {
  const { currentUser: { permissions = [] } = {} } = initialState ?? {};
  const menuPermissions = permissions
    .filter((item: IPermissionItemProps) => item.type === PermissionType.MENU)
    .map((item: IPermissionItemProps) => item.access);
  const btnPermissions = permissions
    .filter((item: IPermissionItemProps) => item.type === PermissionType.BUTTON)
    .map((item: IPermissionItemProps) => item.access);
  // 判断菜单是否有权限
  const hasBtnPerms = (perm: string) => {
    // 判断是否有权限
    return matchPermission(btnPermissions, perm);
  };
  // 获取当前用户所有的页面权限
  const currentPermissions = menuPermissions.reduce(
    (currentObj: Record<string, boolean>, currentValue: string) => {
      currentObj[currentValue] = true;
      return currentObj;
    },
    {},
  );
  return {
    ...currentPermissions,
    hasBtnPerms,
  };
}
